﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using HtmlAgilityPack;
using AutoBuyWinform.utils;

namespace AutoBuyWinform
{
    public partial class WebForm : Form
    {
        private string page;
        private int pageNo=-1;
        private string firstHref = "";
        private System.Threading.AutoResetEvent obj = new System.Threading.AutoResetEvent(false);
        private HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        private HtmlAgilityPack.HtmlDocument chatBodyContext = new HtmlAgilityPack.HtmlDocument();

        public WebForm()
        {
            InitializeComponent();
            //webbrowser静音
            UnmanagedCode.DisableSound();
        }

        public void openUrl(string url)
        {
            webBrowser1.Url = new Uri(url);
        }

        /// <summary>
        /// 读取当前页面内容
        /// </summary>
        /// <returns></returns>
        public string getPageString()
        {
            return webBrowser1.Document.Body.InnerHtml;
        }

        /// <summary>
        /// 打开页面，并返回页面内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string getPage(string url)
        {
            this.pageNo = -1;
            this.firstHref = "";
            webBrowser1.Url = new Uri(url);

            //this.Visible = true;
            do
            {
                Thread.Sleep(100);
                if (webBrowser1.Document != null && webBrowser1.Document.Body != null)
                    page = webBrowser1.Document.Body.OuterHtml;

                Application.DoEvents();
            } while (page == null || !page.Contains("包装样例"));

            return page;
            //webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(readPage);

            //obj.Reset();
            //while (obj.WaitOne(10, false) == false) { Application.DoEvents(); }
            //Console.Write(page);
            //// MessageBox.Show(page);
            //return "";
        }

        public void clickPageNo(int pageNo)
        {
            HtmlElementCollection hc = webBrowser1.Document.GetElementsByTagName("a");
            
           
            HtmlElement e;
            for(int i=hc.Count-1;i>=0;i--)
            {
                e = hc[i];
                if ("paging(p.page)".Equals(e.GetAttribute("ng-click")) && pageNo.ToString().Equals(e.InnerText.Trim()))
                {
                    e.InvokeMember("Click");
                    break;
                }
            }
        }

        /// <summary>
        /// 点击页面按钮跳转页面，并返回页面内容
        /// </summary>
        /// <param name="pageNo"></param>
        /// <returns></returns>
        public string getPageByClickPageNo(int pageNo)
        {
            this.pageNo = pageNo;

            HtmlElementCollection hc = webBrowser1.Document.GetElementsByTagName("a");

            HtmlElement e;
            for (int i = hc.Count - 1; i >= 0; i--)
            {
                e = hc[i];
                if ("paging(p.page)".Equals(e.GetAttribute("ng-click")) && pageNo.ToString().Equals(e.InnerText.Trim()))
                {
                    e.InvokeMember("Click");
                    break;
                }
            }

            string pageNoStr = null;
            string searchPage = null;
            string firstHref = null;
            do
            {
                Thread.Sleep(100);
                try
                {
                    searchPage = webBrowser1.Document.Body.OuterHtml;
                }catch(Exception){
                    continue;
                }

                // 使用預設編碼讀入 HTML
                doc.LoadHtml(searchPage);
                // 裝載Chat body


                chatBodyContext.LoadHtml(doc.DocumentNode.SelectSingleNode("/body").InnerHtml);

                HtmlNodeCollection divs = chatBodyContext.DocumentNode.SelectNodes("child::div");


                HtmlNode div = HtmlAgilityPackUtil.findFirstOneHasAttr(divs, "ng-include");

                firstHref = div.SelectSingleNode("/div/div/div/div[@class='selresult_list_area']/div/div[1]/div[1]/a[1]").GetAttributeValue("href","").Trim();
                if (firstHref.Equals(this.firstHref))
                {
                    Application.DoEvents();
                    continue;
                }

                HtmlNode a = div.SelectSingleNode("./div/div[2]/a[@class='ng-scope ng-binding active']");

                if (a != null)
                {
                    pageNoStr = a.InnerText.Trim();
                    pageNoStr = pageNoStr.Substring(0, pageNo.ToString().Length);
                }


                Application.DoEvents();
            } while (searchPage == null || !searchPage.Contains("包装样例") || !this.pageNo.ToString().Equals(pageNoStr));

            this.firstHref = firstHref;

            
            return searchPage;
        }


        

        //private void readPage(object sender, WebBrowserDocumentCompletedEventArgs e)
        //{
        //    if (pageNo == -1)
        //        return;
        //    string pageNoStr = null;
        //    string searchPage;
        //    MessageBox.Show("in");
        //    if (webBrowser1.ReadyState == WebBrowserReadyState.Complete && e.Url.ToString() == webBrowser1.Url.ToString())
        //    {
        //        do
        //        {
        //            Thread.Sleep(100);

        //            searchPage = webBrowser1.Document.Body.OuterHtml;

        //            // 使用預設編碼讀入 HTML
        //            doc.LoadHtml(searchPage);
        //            // 裝載Chat body
                    

        //            chatBodyContext.LoadHtml(doc.DocumentNode.SelectSingleNode("/body").InnerHtml);

        //            HtmlNodeCollection divs = chatBodyContext.DocumentNode.SelectNodes("child::div");
                    

        //            HtmlNode div = HtmlAgilityPackUtil.findFirstOneHasAttr(divs, "ng-include");

        //            HtmlNode a = div.SelectSingleNode("./div/div[2]/a[@class='active']");

        //            if (a != null)
        //                pageNoStr = a.InnerText.Trim();

        //            Application.DoEvents();
        //        } while (page == null || !searchPage.Contains("包装样例") || !this.pageNo.ToString().Equals(pageNoStr));
        //        obj.Set();
        //    }
            
        //}
    }


   
}
